<?php

namespace app\server;

use think\Exception;

class SendRequestServer
{

    private $cookies = 'cookies_cache';
    private $searchTimeCache = 'vin_search_time';

    private $errorCode = 1000100; // 需要重新入队的标识

    public function send($vin, $params)
    {
        // 获取可用cookie
        $redis = RedisClientSever::getInstance()->redisClientServer();

        $r = $redis->SRANDMEMBER($this->cookies);

        if ($r === null) {
            throw new Exception('获取可用cookie数据失败，请补充');
        }

        // cookie 数据检查
        $cookie = json_decode($r, true);
//        if (!is_array($cookie) || count($cookie) != 5) {
//            throw new Exception('获取可用cookie数据结构错误，请检查');
//        }

        #region构建http请求=====
        // 构建请求体
        $body = json_encode([
            'f6-data-backendSESSIONID' => $cookie['f6-data-backendSESSIONID'],
            'un' => $cookie['un'],
            'sensorsdata2015jssdkcross' => $cookie['sensorsdata2015jssdkcross'],
            'erpLanguage' => $cookie['erpLanguage'],
            'unp' => $cookie['unp'],
            '_up' => $cookie['_up']
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
        $form = [
            'form_params' => [
                'cookie' => $body
            ]
        ];

        // http 请求
        $guzzleClient = new \GuzzleHttp\Client();
        $res = $guzzleClient->request('POST', "http://49.232.137.209:8000/api/vin?vin={$vin}&module_id={$params['module_id']}&key={$params['key']}&data_type={$params['data_type']}", $form)->getBody()->getContents();
//        $res = $guzzleClient->request('POST', "http://121.43.48.175:8000/api/vin?vin={$vin}&module_id={$params['module_id']}&key={$params['key']}&data_type={$params['data_type']}", $form)->getBody()->getContents();
        $res = json_decode($res, true);

        // 此时发生错误，程序往后不再执行，直接返回，并通知到管理员
        if (isset($res['code']) && $res['code'] == 400) {

            if ($res['message'] == '当日访问次数已达上限') {
                $redis->SREM($this->cookies, $r); // 移除可用cookie
                throw new Exception($res['message'] . ' 异常账号：' . $cookie['mobile'], $this->errorCode);
            }

            throw new Exception($res['message']);
        } elseif (isset($res['code']) && $res['code'] == 401) {// 此时是cookie过期，也知识cookie过期，需要更新该账号的cookie，提示更新
            $redis->SREM($this->cookies, $r); // 移除可用cookie
            throw new Exception("账号登录状态超时，请更新cookie，账号为：{$cookie['mobile']}", $this->errorCode); // 需重新入队
        }

        // 其他错误
        if ($res['code'] != 200) {
            $err = '未知错误';
            if (isset($res['msg'])) {
                $err = $res['msg'];
            } elseif (isset($res['message'])) {
                $err = $res['message'];
            }
            throw new Exception($err . '，错误码：' . $res['code'] . $err);
        }

        if (!isset($res['data'])) {
            throw new Exception('数据结构错误-1');
        }

        // 记录该次的查询时间戳
        $redis->set($this->searchTimeCache, time(), 7200);

        return $res;
        #endregion
    }
}